from flask import Flask, Blueprint, render_template, request, jsonify, redirect, url_for, flash
from app.config import create_db_connection

class_list_bp = Blueprint('class_list', __name__)
conn, cursor = create_db_connection()

try:

    cursor.execute('SELECT * FROM class_list WHERE id = 1')
    result = cursor.fetchone()
    if result is None:
        parent_directory = None
        cursor.execute('INSERT INTO class_list (id, name, code, parent_directory) VALUES (1, "默认类别", "", %s)',
                       (parent_directory,))
        conn.commit()  # 使用数据库连接对象提交事务
finally:
    if cursor:
        cursor.close()
    if conn:
        conn.close()

@class_list_bp.route('/class_list')
def class_list():
    conn, cursor = create_db_connection()

    try:
        cursor.execute(
            "SELECT c.id, c.name, c.code, d.name FROM class_list c LEFT JOIN class_list d ON c.parent_directory = d.id")
        class_list = cursor.fetchall()

        return render_template('class/class_list.html', class_list=class_list)
    finally:
        cursor.close()
        conn.close()


@class_list_bp.route('/submit_class', methods=['POST'])
def submit_class():
    name = request.form['class_name']
    code = request.form['class_code']
    parent_directory = request.form['parent_directory']
    if parent_directory != '':
        parent_directory = int(parent_directory)
    else:
        parent_directory = None

    if not name:
        flash('请填写类别名称')
        return redirect('/class_list')

    conn, cursor = create_db_connection()

    try:
        check_duplicate_query = '''
        SELECT name
        FROM class_list
        WHERE name = %s 
        '''

        cursor.execute(check_duplicate_query, [name])
        duplicate_record = cursor.fetchone()

        if duplicate_record:
            flash('该产品类别已存在')
            return redirect('/class_list')

        cursor.execute('INSERT INTO class_list (name, code, parent_directory) \
                        VALUES (%s, %s, %s)', (name, code, parent_directory))

        conn.commit()

        flash('添加类别成功')
        return redirect('/class_list')
    finally:
        cursor.close()
        conn.close()


@class_list_bp.route('/delete/<int:class_id>', methods=['POST'])
def delete(class_id):
    conn, cursor = create_db_connection()

    # 根据ID执行删除操作
    cursor.execute("DELETE FROM class_list WHERE id = %s", [class_id])

    # 提交事务
    conn.commit()
    cursor.close()
    conn.close()

    # 检查是否删除成功
    if cursor.rowcount > 0:
        flash("删除产品类别成功")
    else:
        flash("未找到要删除的产品类别")

    # 返回客户列表页面
    return redirect('/class_list')


@class_list_bp.route('/class_edit/<int:class_id>', methods=['GET'])
def class_edit(class_id):
    conn, cursor = create_db_connection()
    cursor.execute("SELECT * FROM class_list")
    class_list = cursor.fetchall()

    cursor.execute("SELECT * FROM class_list WHERE id = %s", [class_id])
    class_info = cursor.fetchall()
    tuple_info = tuple(t for t in class_info)

    cursor.close()
    conn.close()

    return render_template('class/class_edit.html', class_info=class_info, class_list=class_list)


@class_list_bp.route('/class_edit_update', methods=['POST'])
def class_edit_update():
    class_id = request.form['class_id']
    name = request.form['class_name']
    code = request.form['class_code']
    parent_directory = request.form['parent_directory']

    data = ((class_id, name, code, parent_directory),)

    if parent_directory is not None and parent_directory != 'None':
        parent_directory = int(parent_directory)
    else:
        parent_directory = None

    if not name:
        flash('请填写类别名称')
        return render_template('class/class_edit.html', class_info=data)

    conn, cursor = create_db_connection()

    check_duplicate_query = '''
        SELECT name, code, parent_directory
        FROM class_list
        WHERE name=%s AND code=%s AND parent_directory=%s
        '''

    cursor.execute(check_duplicate_query, (name, code, parent_directory))
    duplicate_record = cursor.fetchone()

    if duplicate_record:
        cursor.close()
        conn.close()
        flash('该产品类别名称已存在')
        return render_template('class/class_edit.html', class_info=data)

    cursor.execute('UPDATE class_list SET name=%s, code=%s, parent_directory=%s WHERE id=%s',
                   (name, code, parent_directory, class_id))

    conn.commit()
    cursor.close()
    conn.close()

    flash('更改类别成功')
    return redirect('/class_list')
